//
//  HomeViewController.swift
//  JIMWeiBo
//
//  Created by 陈恒均 on 2018/2/7.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class HomeViewController: BaseViewController {
    // MARK:- 属性
    
    var tempCount : Int = 0
    var photoBrowerAnimator : PhotoBrowerAnimator = PhotoBrowerAnimator()
    var tipLabel : UILabel = UILabel()
    var viewModels : [StatusViewModel] = [StatusViewModel]()
    
    
    // MARK:- 懒加载属性
    lazy var titleBtn :TitleButton = TitleButton()
    lazy var popoverAnimator = PopoverAnimator { [weak self] (presented) in
        self!.titleBtn.isSelected = presented
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        visitorView.addRotationAnmi()
        
        if !isLogin {
            return
        }
        
        
        popoverAnimator.presentedFrame = CGRect(x: 120, y: 55, width: 150, height: 250)
        
        setupNavBar()
        
//        loadStatuses(isNewData: true)
        
//        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 200;
        
        
        setupHeaderView()
        setupFooterView()
        
        setupTipLabel()
        
        setupNotifications()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

   
}
// MARK:- 设置UI界面
extension HomeViewController
{
    func setupNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        titleBtn.setTitle("GeekCoderJim", for: .normal)
        titleBtn.addTarget(self, action: #selector(HomeViewController.titleBtnClick), for: .touchUpInside)
        navigationItem.titleView = titleBtn
    }
    private func setupHeaderView()
    {
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadNewStatuses))
        
        header?.setTitle("下拉刷新", for: .idle)
        header?.setTitle("释放更新", for: .pulling)
        header?.setTitle("加载中...", for: .refreshing)
        
        self.tableView.mj_header = header
        tableView.mj_header.beginRefreshing()
        
    }
    private func setupFooterView(){
        tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadMoreStatuses))
    }
    
    private func setupTipLabel(){
        navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
        
        tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.main.bounds.width, height: 32)
        
        tipLabel.backgroundColor = UIColor.orange
        tipLabel.textColor =  UIColor.white
        tipLabel.font = UIFont.systemFont(ofSize: 14)
        tipLabel.textAlignment = .center
        tipLabel.isHidden = true
    }
    private func setupNotifications(){
        NotificationCenter.default.addObserver(self, selector:#selector(HomeViewController.showPhotoBrowser(note:)), name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: nil)
    }
  
    
}
// MARK:- 事件监听
extension HomeViewController
{
     @objc private func titleBtnClick() {
    
        
        let popoverVc = PopoverViewController()
        
        popoverVc.modalPresentationStyle = .custom
        
        popoverVc.transitioningDelegate = popoverAnimator;
        
        
        present(popoverVc, animated: true, completion: nil)
     
        
    }
    
    @objc private func showPhotoBrowser(note : NSNotification){
        let indexPath = note.userInfo![ShowPhotoBrowserIndexKey] as! NSIndexPath
        let picUrls = note.userInfo![ShowPhotoBrowserUrlsKey] as! [NSURL]
        let object = note.object as! PicCollectionView
        
        
        let photoBrowerVc = PhotoBrowserController(indexPath: indexPath, picUrls: picUrls )
        
        photoBrowerVc.modalPresentationStyle = .custom
        
        photoBrowerVc.transitioningDelegate = photoBrowerAnimator
        
        ///设置动画代理
        photoBrowerAnimator.presentedDelegate = object
        photoBrowerAnimator.indexPath = indexPath
        photoBrowerAnimator.dismissDelegate = photoBrowerVc
        
        present(photoBrowerVc, animated: true, completion: nil)
  
    }
}

// MARK:- 请求数据

extension HomeViewController
{
    @objc private func loadNewStatuses(){
        loadStatuses(isNewData: true)
    }
    
    @objc private func loadMoreStatuses(){
        loadStatuses(isNewData: false)    }
    
    func loadStatuses(isNewData : Bool) {
        
        var since_id :String?
        var max_id :String?
        
        if isNewData {
            since_id = viewModels.first?.status?.mid 
        }else{
            max_id = viewModels.last?.status?.mid
//            max_id = max_id == 0 ? 0 : (max_id - 1)
        }
        
        
        NetworkTools.shareInstance.loadStatuses(since_id: since_id, max_id: max_id) { (result, error) in
            if error != nil
            {
                return
            }
            guard let resultArray = result else{
                return
            }
            //    print(resultArray)
            
            //遍历微博对应的字典
            
            var tempViewModel = [StatusViewModel]()
            for statusDict in resultArray
            {
                let status  = Status(dict: statusDict)
                let viewModel = StatusViewModel(status: status)
                tempViewModel.append(viewModel)
            }
            if(isNewData){
                self.viewModels = tempViewModel + self.viewModels
                self.tempCount = tempViewModel.count
                self.showTipLabel(count: self.tempCount)
            }else
            {
                self.viewModels  = self.viewModels + tempViewModel
            }
            
            
            //缓存图片
            self.cacheImage(viewModels: self.viewModels)
        }
    }
    
    private func cacheImage(viewModels : [StatusViewModel]){
        
        let group = DispatchGroup()
        
        for viewModel in viewModels {
            for picURl in viewModel.picURLs{
                
                group.enter()
                SDWebImageManager.shared().imageDownloader?.downloadImage(with: picURl as URL, options: [], progress: nil, completed: { (_, _, _, _) in
                    
//                    print("下载了一张图片")
                    group.leave()
                })

            }
            
        }
        
        group.notify(queue: DispatchQueue.main, work:DispatchWorkItem(block: {            
//            print("刷新表格")
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing(completionBlock: {
                self.showTipLabel(count: self.tempCount)
            })
            self.tableView.mj_footer.endRefreshing()
            
            
            
        }))
    }
    
    
    private func showTipLabel(count : Int){
        tipLabel.isHidden = false
        tipLabel.text = count == 0 ? "没有数据" : "\(count) 条新微博"
        
        UIView.animate(withDuration: 1.0, animations: {
            self.tipLabel.frame.origin.y = 44
        }) { (_) in
            UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: {
                self.tipLabel.frame.origin.y = 10
            }, completion: { (_) in
                self.tipLabel.isHidden = true
            })
        }
    }
}
// MARK:- tableView的数据源方法
extension HomeViewController
{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModels.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as! HomeViewCell
        
        let viewModel = viewModels[indexPath.row]
        cell.viewModel = viewModel
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let viewModel = viewModels[indexPath.row]
        return viewModel.cellHeight
        
    }
}








